package com.shantoo.databinding;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.itheima.retrofitutils.Request;

import java.util.List;

/**
 * RecyclerView 的Activity基类
 * 实现recyclerview 上拉加载、下拉刷新、网络出错、数据为空等功能
 */
public abstract class BaseRecyclerViewActivity<T> extends AppCompatActivity {
    private int page = 1;
    protected RecyclerView mRecyclerView;
    protected BaseQuickAdapter mQuickAdapter;
    protected View notDataView;
    protected View errorView;
    protected BaseQuickAdapter<T, BaseViewHolder> mAdapter;
    protected SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean mError = true;
    private boolean mNoData = true;
    protected final static int PAGE_SIZE = 3;
    Request request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        create();
        refreshData();
    }

    public abstract BaseQuickAdapter<T, BaseViewHolder> initAdapter();

    public abstract Request initRequest();

    public abstract SwipeRefreshLayout initSwipeRefreshLayout();

    public abstract RecyclerView initRecyclerView();

    private RecyclerView.LayoutManager mLayoutManager;

    public void setRecyclerViewManager(RecyclerView.LayoutManager layoutManager){
        this.mLayoutManager = layoutManager;
    }

    private void create() {
        mSwipeRefreshLayout = initSwipeRefreshLayout();
        mRecyclerView = initRecyclerView();
        mAdapter = initAdapter();
        request = initRequest();
        request .putParams("page",page);
        notDataView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeView();
            }
        });
        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) mRecyclerView.getParent(), false);
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeView();
            }
        });

        mSwipeRefreshLayout.setRefreshing(true);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));

        if(mLayoutManager == null){
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        }else{
            mRecyclerView.setLayoutManager(mLayoutManager);
        }
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        if (mAdapter != null) {
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    refreshData();
                }
            });
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
            mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    loadMoreData();
                }
            }, mRecyclerView);
        }
    }

    private void changeView() {
        mQuickAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mRecyclerView.getParent());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mError) {
                    mQuickAdapter.setEmptyView(errorView);
                    mError = false;
                } else {
                    if (mNoData) {
                        mQuickAdapter.setEmptyView(notDataView);
                        mNoData = false;
                    } else {
                        // refreshData();
                        // mQuickAdapter.setNewData(newData);
                    }
                }
            }
        },1000);
    }

    public abstract void doOnRefreshData(BaseQuickAdapter<T, BaseViewHolder> adapter, Request request);
    public abstract void doOnLoadMoreData(BaseQuickAdapter<T, BaseViewHolder> adapter, Request request);

    private void refreshData() {
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        doOnRefreshData(mAdapter,request);

//        ItheimaHttp.send(request, new HttpResponseListener<BaseListResponse<T>>() {
//            @Override
//            public void onResponse(BaseListResponse<T> response, Headers headers) {
//                List<T> data = response.getData();
//                setData(true,data);
//                Toast.makeText(TyslApp.getContext(), "refresh", Toast.LENGTH_SHORT).show();
//                mAdapter.setEnableLoadMore(true);
//                mSwipeRefreshLayout.setRefreshing(false);
//            }
//
//            @Override
//            public void onFailure(Call call, Throwable e) {
//                Toast.makeText(TyslApp.getContext(), "网络请求出错", Toast.LENGTH_LONG).show();
//                 mAdapter.setEnableLoadMore(true);
//                mSwipeRefreshLayout.setRefreshing(false);
//            }
//        });
    }

    private void loadMoreData() {
        doOnLoadMoreData(mAdapter,request);
        /*ItheimaHttp.send(request, new HttpResponseListener<BaseListResponse<T>>() {
            @Override
            public void onResponse(BaseListResponse<T> response, Headers headers) {
                Toast.makeText(TyslApp.getContext(), "loadMore", Toast.LENGTH_SHORT).show();
                setData(false, response.getData());
            }

            @Override
            public void onFailure(Call call, Throwable e) {
                mAdapter.loadMoreFail();
                Toast.makeText(TyslApp.getContext(), "网络请求出错", Toast.LENGTH_LONG).show();
            }
        });*/
    }

    public void setData(boolean isRefresh, List<T> data) {
        page++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
            Toast.makeText(this, "no more data", Toast.LENGTH_SHORT).show();
        } else {
            mAdapter.loadMoreComplete();
        }
    }
}
